from fastapi import APIRouter, HTTPException, Depends
from api.common import CategoryCreate, CategoryResponse, get_document_manager

router = APIRouter(prefix="/categories", tags=["分类"])


@router.post("/", response_model=CategoryResponse)
async def create_category(category: CategoryCreate, doc_manager=Depends(get_document_manager)):
    """创建新的分类"""
    try:
        category_id = doc_manager.create_category(category.name, category.description)
        return {"id": category_id, "name": category.name, "description": category.description}
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"创建分类失败: {str(e)}")


@router.get("/", response_model=list[CategoryResponse])
async def get_categories(doc_manager=Depends(get_document_manager)):
    """获取所有分类"""
    categories = doc_manager.get_all_categories()
    return [{"id": cat[0], "name": cat[1], "description": cat[2]} for cat in categories]


@router.get("/{category_id}", response_model=CategoryResponse)
async def get_category(category_id: int, doc_manager=Depends(get_document_manager)):
    """通过ID获取分类"""
    category = doc_manager.get_category_by_id(category_id)
    if not category:
        raise HTTPException(status_code=404, detail="分类不存在")
    return {"id": category[0], "name": category[1], "description": category[2]}


@router.put("/{category_id}", response_model=CategoryResponse)
async def update_category(category_id: int, category: CategoryCreate, doc_manager=Depends(get_document_manager)):
    """更新分类信息"""
    try:
        success = doc_manager.update_category(category_id, category.name, category.description)
        if not success:
            raise HTTPException(status_code=404, detail="分类不存在")
        return {"id": category_id, "name": category.name, "description": category.description}
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"更新分类失败: {str(e)}")